package com.mandao.oneplat.boot.handler;

import com.mandao.oneplat.boot.context.OneContext;
import com.mandao.oneplat.boot.context.OneResponse;
import com.mandao.oneplat.boot.util.CollectionUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.HttpUtil;

import static io.netty.channel.ChannelFutureListener.CLOSE;
import static io.netty.handler.codec.http.HttpHeaderNames.CONNECTION;
import static io.netty.handler.codec.http.HttpHeaderNames.SET_COOKIE;
import static io.netty.handler.codec.http.HttpHeaderValues.KEEP_ALIVE;

/**
 * Created by sunson on 2017/3/23.
 */
public class OneServerPostHandler extends ChannelOutboundHandlerAdapter {

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        if (msg instanceof OneContext) {
            OneContext oneContext = (OneContext) msg;
            OneResponse oneResponse = oneContext.getOneResponse();
            HttpResponse httpResponse = oneResponse.getHttpResponse();
            if (httpResponse == null) {
                httpResponse = OneResponse.BAD_RESPONSE;
            }
            // 处理Cookie
            if (CollectionUtil.isNotEmpty(oneResponse.getCookies())) {
                httpResponse.headers().add(SET_COOKIE, oneResponse.getCookies());
            }
            //
            if (!HttpUtil.isKeepAlive(oneContext.getHttpRequest()) || OneResponse.BAD_RESPONSE.status().equals(httpResponse.status())) {
                ctx.write(httpResponse).addListener(CLOSE);
            } else {
                oneResponse.getHttpResponse().headers().set(CONNECTION, KEEP_ALIVE);
                ctx.write(httpResponse);
            }
        }
    }
}
